package com.gupao.xhc.homework.zookeeper.chosemaster;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkException;
import org.I0Itec.zkclient.exception.ZkInterruptedException;
import org.apache.zookeeper.CreateMode;

public class MasterCompetitor implements Runnable {

	private ZkClient zkClient;
    private String name;
    private CountDownLatch downLatch ;
    private long useMaterTime = 2;
    private IZkDataListener listener;
    
    public MasterCompetitor() {
        super();
    }

    public MasterCompetitor(ZkClient zkClient, String name, CountDownLatch downLatch) {
        super();
        this.zkClient = zkClient;
        this.name = name;
        this.downLatch = downLatch;
        addWatcher();
    }

    private void addWatcher(){
        zkClient.subscribeDataChanges(ChoseMaster.MASTER_PATH, listener = new IZkDataListener() {
            
            @Override
            public void handleDataChange(String s, Object o) throws Exception {

            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                System.out.println("master被删除了，["+name+"] 开始争抢master");
                competeMaster();
            }
        });
    }
    
    @Override
    public void run(){
    	competeMaster();
    }
    
    public boolean competeMaster() {
        try {
        	downLatch.await();
        	System.out.println(name + " 开始竞争Master");
//        	if(zkClient.readData(ChoseMaster.MASTER_PATH).equals(name)){
//        		System.out.println(name + " 已经获的了Master，不必再竞争Master");
//        	}
            String master = zkClient.create(ChoseMaster.MASTER_PATH, name, CreateMode.PERSISTENT);
            System.out.println(name + " 注册成为master!!!!" );
            TimeUnit.SECONDS.sleep(useMaterTime);
            if(zkClient.delete(ChoseMaster.MASTER_PATH)){
            	zkClient.delete(ChoseMaster.MASTER_PATH);
            	System.out.println(name + " 使用完Master，删除了Master");
            	zkClient.unsubscribeDataChanges(ChoseMaster.MASTER_PATH, listener);
            }
            
        } catch (Exception e) {

        	System.out.println("Master 已经被注册...，  "+name+" 竞争失败");
            if(zkClient.exists(ChoseMaster.MASTER_PATH)){
            	try {
            		TimeUnit.SECONDS.sleep(1);
					competeMaster();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
            	
            }
        }
        return true;
    }
}
